package com.ellecity06.cwhiskymall.ui.search.result

import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.QuickAdapterHelper
import com.chad.library.adapter.base.layoutmanager.QuickGridLayoutManager
import com.chad.library.adapter.base.loadState.LoadState
import com.chad.library.adapter.base.loadState.trailing.TrailingLoadStateAdapter
import com.ellecity06.common.adapter.CustomLoadMoreAdapter
import com.ellecity06.common.base.BaseMvvmFragment
import com.ellecity06.common.ktx.addGridDecoration
import com.ellecity06.common.ktx.finishRefresh
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.ktx.theme
import com.ellecity06.common.widgets.dialog.showAlert
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.adapter.SearchGoodAdapter
import com.ellecity06.cwhiskymall.databinding.FragmentSearchResultBinding
import com.ellecity06.cwhiskymall.ui.search.SearchIntent
import com.ellecity06.cwhiskymall.ui.search.SearchState
import com.ellecity06.cwhiskymall.ui.search.SearchViewModel
import com.ellecity06.cwhiskymall.ui.webview.WebHelper
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent

/**
 * @author ellecity06
 * @time 2024/11/2 10:17
 * @des 搜索结果页面
 */
class SearchResultFragment : BaseMvvmFragment<FragmentSearchResultBinding, SearchViewModel>(),
    SwipeRefreshLayout.OnRefreshListener, TrailingLoadStateAdapter.OnTrailingListener {
    private val keyword: String by lazy { arguments?.getString(KEYWORD) ?: "" }
    private val searchViewModel: SearchViewModel by lazy { ViewModelProvider(requireActivity())[SearchViewModel::class.java] }
    private val adapter: SearchGoodAdapter by lazy { SearchGoodAdapter() }

    companion object {
        private const val KEYWORD = "keyword"

        /**
         * 搜索用
         */
        fun newInstance(keyword: String): SearchResultFragment {
            val fragment = SearchResultFragment()
            val bundle = Bundle()
            bundle.putString(KEYWORD, keyword)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun lazyInit() {
        initEvent()
        initObserver()
    }

    private fun initEvent() {
        binding.refreshLayout.setOnRefreshListener(this)
    }


    private lateinit var adapterHelper: QuickAdapterHelper
    override fun initView() {
        binding.refreshLayout.theme()
        binding.rvGood.layoutManager = QuickGridLayoutManager(requireActivity(), 2)
        val loadMoreAdapter = CustomLoadMoreAdapter()
        loadMoreAdapter.setOnLoadMoreListener(this)
//        loadMoreAdapter.isAutoLoadMore = true
        binding.rvGood.addGridDecoration()
        adapter.isEmptyViewEnable = true

        adapter.setEmptyViewLayout(requireActivity(), R.layout.layout_empty_view)
        adapter.animationEnable = true

        adapter.setItemAnimation(BaseQuickAdapter.AnimationType.ScaleIn)
        adapterHelper = QuickAdapterHelper.Builder(adapter)
            .setTrailingLoadStateAdapter(loadMoreAdapter)
            .build()

        binding.rvGood.adapter = adapterHelper.adapter
        adapter.setOnItemClickListener { _, _, position ->
            val item = adapter.getItem(position)
            WebHelper.goodDetails(requireActivity(),item?.id)
        }

    }

    fun refresh() {
        lifecycleScope.launchWhenCreated {
            searchViewModel.intentChannel.send(SearchIntent.Refresh)
        }
    }

    fun loadMore() {
        lifecycleScope.launchWhenCreated {
            searchViewModel.intentChannel.send(SearchIntent.LoadMore)
        }
    }
    private fun initObserver() {
        searchViewModel.state.observeEvent(requireActivity()) {
            when (it) {
                is SearchState.RefreshSuccess -> {
                    adapter.submitList(it.list)
                    binding.refreshLayout.finishRefresh()
                    if (it.hasMore) {
                        adapterHelper.trailingLoadState = LoadState.NotLoading(false)
                    } else {
                        adapterHelper.trailingLoadState = LoadState.None
                    }
                }
                is SearchState.LoadMoreSuccess -> {
                    adapter.addAll(it.list)
                    adapterHelper.trailingLoadState = LoadState.NotLoading(!it.hasMore)
                }
                is SearchState.LoadError -> {
                    binding.refreshLayout.finishRefresh()
                }
                is SearchState.NoMore -> {
                    binding.refreshLayout.finishRefresh()
                    adapterHelper.trailingLoadState = LoadState.None
                }
                else -> {}
            }
        }
    }

    override fun inflateBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentSearchResultBinding {
        return FragmentSearchResultBinding.inflate(inflater, container, false)
    }

    override fun onRefresh() {
        refresh()
    }

    override fun onFailRetry() {
        loadMore()
    }

    override fun onLoad() {
        loadMore()
    }


}